package org.siberia.server.model;

import java.io.Serializable;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.Transient;
import javax.persistence.Version;

import com.google.gwt.user.client.rpc.IsSerializable;

@Entity
public class ActionSuite
{
	@Id
	@Column(name = "id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long id;
	
	/* name */
	public String name;
	
	/* description */
	public String description;
	
	/** link to an existing user */
//	@JoinColumn
	public Long ownerKey;
	
	@Transient
	public User owner;
	
	/** version */
	@Version
	public Integer version;
	
	public static EntityManager entityManager()
	{
		return EMF.get().createEntityManager();
	}
	
	public static ActionSuite findActionSuite(Long _id)
	{
		ActionSuite result = null;
		
		if ( _id != null )
		{
			EntityManager manager = entityManager();
			try
			{	result = manager.find(ActionSuite.class, _id); }
			finally
			{	manager.close(); }
		}
		
		return result;
	}
	
	public User getUser()
	{
		if ( this.owner == null )
		{
			this.owner = User.findUser(this.ownerKey);
		}
		return this.owner;
	}
	
	public void persist()
	{
		EntityManager manager = entityManager();
		try
		{	manager.persist(this); }
		finally
		{	manager.close(); }
	}
	
	public static List<ActionSuite> findSuitesForUser(Long _userKey)
	{
		List<ActionSuite> suites = null;
		
		EntityManager manager = entityManager();
		
		try
		{
			Query query = manager.createQuery("select o from ActionSuite o where o.ownerKey=:userKey");
			query.setParameter("userKey", _userKey);
			suites = query.getResultList();
		}
		finally
		{
			manager.close();
		}
		
		return suites;
	}
	
	public static void deleteAll()
	{
		EntityManager manager = entityManager();
		
		try
		{
			Query query = manager.createQuery("DELETE from ActionSuite o");
			query.executeUpdate();
		}
		finally
		{	manager.close(); }
	}
}
